package com.platform.utils.uuid;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class RandomUtil
{
    private static Set<Integer> exists = new HashSet<>();
    
    private static Random random = new Random();
    
    private static double length4 = Math.pow(10, 3);
    
    private static long current = System.currentTimeMillis();
    
    public static String generate(int length)
    {
        return String.valueOf(exclude(length));
    }
    
    private static int random(int length)
    {
        double tmp = 0;
        switch (length)
        {
            case 4:
                tmp = length4;
                break;
            default:
                tmp = Math.pow(10, length - 1);
        }
        
        int code = random.nextInt(new Integer("8" + ((int)tmp - 1))) + (int)tmp;
        
        return code;
    }
    
    private static int exclude(int length)
    {
        synchronized (exists)
        {
            int code = random(length);
            long opr = System.currentTimeMillis();
            if (Math.abs(current - opr) > 1000)
            {
                current = opr;
                exists.clear();
            }
            if (exists.contains(code))
            {
                return exclude(length);
            }
            
            exists.add(code);
            return code;
        }
    }
}
